import { Context, Next } from 'koa';

// 自定义错误类
export class AppError extends Error {
  statusCode: number;
  status: string;
  isOperational: boolean;

  constructor(message: string, statusCode: number) {
    super(message);
    this.statusCode = statusCode;
    this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
    this.isOperational = true; // 标记为可操作的错误

    Error.captureStackTrace(this, this.constructor);
  }
}

// 错误处理中间件
export const errorHandler = () => async (ctx: Context, next: Next) => {
  try {
    await next();

    // 处理404错误
    if (ctx.status === 404 && !ctx.body) {
      ctx.status = 404;
      ctx.body = {
        status: 'fail',
        message: `找不到路径: ${ctx.path}`,
      };
    }
  } catch (err: any) {
    console.error('错误:', err);

    // 默认错误状态码
    ctx.status = err.statusCode || err.status || 500;

    // 开发环境返回详细错误信息
    const isDev = process.env.NODE_ENV === 'development';

    ctx.body = {
      status: err.status || 'error',
      message: err.message,
      ...(isDev && { stack: err.stack, error: err }),
    };
  }
}; 